#! C:\Perl\bin\perl.exe

# Copyright (c) 2010, College Center for Library Automation

# See the included Copyright.txt file for full license

use strict;
use warnings;
use Date::Calc qw(Today);

#
# execute all scraper programs defined in table vendors
#
#

use avsCommon;

my ($dbhscrapes, $sqlscrapes, $sthscrapes);
my ($scraper, $vendorname);

my $runforcollegeid = paramscheck();

# connect to db
$dbhscrapes = DBI->connect('dbi:ODBC:AutomatedVendorStats' ,,, { 'PrintError' => 1, 'RaiseError' => 1 })
	or die '#error: dbhlogin connect: ' . DBI->errstr;

# sql to get all scraper programs
$sqlscrapes = qq/SELECT Scraper, Name FROM Vendors WHERE NOT Scraper IS NULL/;

$sthscrapes = $dbhscrapes->prepare($sqlscrapes)
	or die "#error: unable to prepare $sqlscrapes ".$dbhscrapes->errstr;

$sthscrapes->execute()
	or die "#error: execute sthscrapes:" . $dbhscrapes->errstr;
	
$sthscrapes->bind_columns(\$scraper, \$vendorname)
	or die "#error: bind sthlogin: ".$dbhscrapes->errstr;
	
$sthscrapes->fetch
	or die "#error: unable to retrieve information for $scraper ", ($runforcollegeid) ? "and collegeid $runforcollegeid" : '';

# delete the old files
#unlink glob("../Logs/*.log");

my $errorflag = 0;

# loop through logininformation table to get all scraper program names
do {
	my $logfile = "../Logs/$vendorname-" . sprintf("%4d%02d%02d",Today) . '.log';
	my $nextcommand = "perl $scraper ".join('-',@begdate).' '.join('-',@enddate)." $runforcollegeid >$logfile 2>&1";

	print scalar localtime, " $nextcommand\n";
	system $nextcommand;
	print scalar localtime, " $scraper completed\n\n";
	
	# check for error statements which appear at the top of the log. if found print them to the runall log
	open AFIL, "<$logfile"
		or die "could not open file: $!";
	local $/=undef;
	my	$content = <AFIL>;
	close AFIL;
		
	while ($content =~ /(\#error.*?)\n/gs) {
		$errorflag = 1;
		print "$1\n";
	}
		
} while ($sthscrapes->fetch);

if ($errorflag == 0) {
	foreach my $rpt ('L010', 'L011', 'L012', 'L013', 'YTDComparison') {
		my $logfile = "../Logs/$rpt-" . sprintf("%4d%02d%02d",Today) . ".log";
		my $nextcommand = "perl rpt_$rpt.pl >$logfile 2>&1";

		print scalar localtime, " $nextcommand\n";
		system $nextcommand;
		print scalar localtime, " $rpt completed\n\n";
	}
}
	